package com.xin.data.turning.device


import android.content.Intent
import android.net.Uri
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.IntentSenderRequest
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.tasks.Task
import com.google.android.play.core.appupdate.AppUpdateManager
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.appupdate.AppUpdateInfo
import com.google.android.play.core.appupdate.AppUpdateOptions
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.UpdateAvailability
import kotlinx.coroutines.tasks.await

/**
 * 应用内更新辅助类
 *
 * 前提导入：
 * implementation 'com.google.android.play:app-update:2.1.0'
 * implementation 'com.google.android.play:app-update-ktx:2.1.0'
 * implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.7.3'
 *
 */
class ImmediateUpdateManager(
    private val activity: AppCompatActivity,
    private val forceUpdate: Boolean = false, // 是否需要强制更新
    private val updateLauncher: ActivityResultLauncher<IntentSenderRequest>,
    private val onForceUpdateRedirect: (() -> Unit)? = null // 可选强更跳转商店前通知
) {

    private val appUpdateManager: AppUpdateManager = AppUpdateManagerFactory.create(activity)

    /**
     * 判断是否满足立即更新启动条件
     */
    private fun AppUpdateInfo?.canStartImmediateUpdate(): Boolean =
        this?.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE &&
                this.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)

    /**
     * 判断是否满足恢复更新流程条件
     */
    private fun AppUpdateInfo?.canResumeUpdate(): Boolean =
        this?.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS

    /**
     * 协程版
     * 检查更新并启动立即更新流程
     * @param onNoUpdate 无更新时回调
     */
    suspend fun checkAndStartUpdateAsync(onNoUpdate: () -> Unit) {
        try {
            val info: AppUpdateInfo? = appUpdateManager.appUpdateInfo.await()
            if (info == null || !info.canStartImmediateUpdate()) {
                println("无法立即更新或无更新")
                handleNoUpdate(onNoUpdate)
                return
            }

            val started = appUpdateManager.startUpdateFlowForResult(
                info,
                updateLauncher,
                AppUpdateOptions.newBuilder(AppUpdateType.IMMEDIATE).build()
            )
            if (!started) {
                println("Google 更新 UI 未弹出")
                handleNoUpdate(onNoUpdate)
            }
        } catch (e: Exception) {
            println("异常 ${e.localizedMessage}")
            handleNoUpdate(onNoUpdate)
        }
    }

    /**
     * 非协程版
     * 检查更新并启动立即更新流程
     * @param onNoUpdate 无更新时回调
     */
    fun checkAndStartUpdate(onNoUpdate: () -> Unit) {
        try {
            appUpdateManager.appUpdateInfo
                .addOnSuccessListener { info ->
                    try {
                        if (info == null || !info.canStartImmediateUpdate()) {
                            println("无法立即更新或无更新")
                            handleNoUpdate(onNoUpdate)
                            return@addOnSuccessListener
                        }

                        val started = appUpdateManager.startUpdateFlowForResult(
                            info,
                            updateLauncher,
                            AppUpdateOptions.newBuilder(AppUpdateType.IMMEDIATE).build()
                        )
                        if (!started) {
                            println("Google 更新 UI 未弹出")
                            handleNoUpdate(onNoUpdate)
                        }

                    } catch (e: Exception) {
                        println("异常 ${e.localizedMessage}")
                        handleNoUpdate(onNoUpdate)
                    }
                }
                .addOnFailureListener { e ->
                    println("异常 ${e.localizedMessage}")
                    handleNoUpdate(onNoUpdate)
                }
        } catch (e: Exception) {
            println("异常 ${e.localizedMessage}")
            handleNoUpdate(onNoUpdate)
        }
    }

    /**
     * 协程版
     * 恢复未完成的更新流程
     */
    suspend fun resumeIfInProgressAsync() {
        try {
            val info = appUpdateManager.appUpdateInfo.await() ?: return
            if (info.canResumeUpdate()) {
                try {
                    appUpdateManager.startUpdateFlowForResult(
                        info,
                        updateLauncher,
                        AppUpdateOptions.newBuilder(AppUpdateType.IMMEDIATE).build()
                    )
                } catch (e: Exception) {
                    println("恢复更新异常 ${e.localizedMessage}")
                }
            }
        } catch (e: Exception) {
            println("恢复更新异常 ${e.localizedMessage}")
        }
    }

    /**
     * 非协程版
     * 恢复未完成的更新流程
     */
    fun resumeIfInProgress() {
        try {
            val infoTask: Task<AppUpdateInfo> = appUpdateManager.appUpdateInfo
            infoTask.addOnSuccessListener { info ->
                if (info == null) return@addOnSuccessListener
                if (info.canResumeUpdate()) {
                    try {
                        appUpdateManager.startUpdateFlowForResult(
                            info,
                            updateLauncher,
                            AppUpdateOptions.newBuilder(AppUpdateType.IMMEDIATE).build()
                        )
                    } catch (e: Exception) {
                        println("恢复更新异常 ${e.localizedMessage}")
                    }
                }
            }
        } catch (e: Exception) {
            println("恢复更新异常 ${e.localizedMessage}")
        }
    }

    /**
     * 跳转应用商店详情页, 目的是让用户手动更新
     */
    private fun goToPlayStorePage() {
        val packageName = activity.packageName
        try {
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$packageName"))
            intent.setPackage("com.android.vending")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            activity.startActivity(intent)
        } catch (e: Exception) {
            try {
                val intent = Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("https://play.google.com/store/apps/details?id=$packageName")
                )
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                activity.startActivity(intent)
            } catch (e: Exception) {
                println("无法跳转商店: ${e.localizedMessage}")
            }
        }
    }

    /**
     * 处理回调
     */
    private fun handleNoUpdate(onNoUpdate: () -> Unit) {
        try {
            if (forceUpdate) {
                println("强制更新未触发，跳转 Play 商店")
                onForceUpdateRedirect?.invoke()
                goToPlayStorePage()
            } else {
                onNoUpdate()
            }
        } catch (e: Exception) {
            //
        }
    }
}